export default {
  // 树节点重组
  treeToSelectArryObj(data, selectField, checkField) {
    const vm = this;
    let tmp = [];
    Array.from(data).forEach(function(record) {
      if (record[checkField] === 'Y') {
        let _data = {};
        if (record.children && record.children.length > 0) {
          _data.value = record[selectField];
          _data.hasChildren = true;
        } else {
          _data.value = record[selectField];
          _data.hasChildren = false;
        }
        tmp.push(_data);
      }
      if (record.children && record.children.length > 0) {
        let children = vm.treeToSelectArryObj(
          record.children,
          selectField,
          checkField
        );
        tmp = tmp.concat(children);
      }
    });
    return tmp;
  },
  // 通过key返回对象
  findItem(data, col, para) {
    let res = {};
    if (data.length > 0) {
      res = data.find((item) => {
        return item[col] === para;
      });
    }
    return res;
  },
  // 遍历返回key对应的数组集合
  arrayIdList(data, id) {
    let arry = [];
    if (data.length > 0) {
      data.forEach((res) => {
        arry.push(res[id]);
      });
    }
    return arry;
  },
  // 检验手机
  regExpPhone(phone) {
    let phoneReg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
    return phoneReg.test(phone);
  },
  // 检验特殊字符
  specialStr(val) {
    let regStr = /[#%&?]/im;
    if (regStr.test(val)) {
      return false;
    } else {
      return true;
    }
  },
  // 检验日期
  regDateTime(str) {
    let myDate = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
    // "日期格式不正确，正确格式为：2014-01-01"
    return myDate.test(str);
  },
  // 检验数字
  regExNumber(num) {
    let number = /^\d+$/;
    return number.test(num);
  },
  // 检验正双精度
  regExDouble(num) {
    let number = /^\d+(\.\d+)?$/;
    return number.test(num);
  },
  // 非负数
  regPosNumber(num) {
    let number = /^\d+(\.{0,1}\d+){0,1}$/;
    return number.test(num);
  },
  // 检验邮箱
  regExpEmail(email) {
    let emailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    return emailReg.test(email);
  },
  // 校验身份证(18位)
  regExIdCard(id) {
    let idCard = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|x|X)$/;
    return idCard.test(id);
  },
  /**
   * 检查当前用户是否有权限
   * chargeAccountApprove：合同挂账
   * contractApprove：合同审批
   * contractChangeApprove：合同变更
   * payApplyApprove：付款申请审批
   * payAppApprove：付款审批
   * phaseReportApprove：汇报审批
   */
  hasAuthority(authName) {
    const vm = this;
    let obj = {};
    if (vm.$global.authorities !== '') {
      let data = JSON.parse(vm.$global.authorities);
      obj = vm.findItem(data, 'settingCode', authName);
    }
    if (obj) {
      if (obj.isEffect === 'S') {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  },
  hasAuthorities(authName) {
    const vm = this;
    let authorities = vm.$global.userInfo.authorities;
    let ret = false;
    for (let index = 0; index < authorities.length; index++) {
      if (authorities[index].authority === authName) {
        ret = true;
      }
    }
    if (ret) {
      return true;
    } else {
      return false;
    }
  },
  // 去除html样式
  removeStyle(contnet) {
    let _str = contnet || '';
    let regex = /id=".*?"|class=".*?"|style=".*?"/gi;
    if (_str.length > 0) {
      _str = contnet.replace(regex, '');
    }
    _str = _str.replace(/<embed[^>]*>/gi, '');
    return _str;
  },
  dealImgUrl(str, url) {
    let _str = str || '';
    if (_str.length > 0 && (url !== null || url !== '')) {
      _str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function(
        match,
        capture
      ) {
        _str = _str.replace(capture, url + capture.substr(2));
      });
    }
    return _str;
  },
  // keyToValue
  keyToValue(data, keyName, keyVal, resName) {
    let obj = {};
    if (data.length > 0) {
      obj = data.find((item) => item[keyName] === keyVal);
    }
    return obj[resName];
  },
  valueToObj(data, value) {
    let res = {};
    if (data.length > 0) {
      data.forEach((item) => {
        if (item.contractId === value) {
          res = item;
        }
      });
    }
    return res;
  },
  // subString
  subMyStr(str, num) {
    let _str = '';
    if (str.length > num) {
      _str = str.substr(0, num) + '...';
    } else {
      _str = str;
    }
    return _str;
  },
  // 时间格式化
  formatTime(fmt, v) {
    if (v) {
      let date = new Date(v);
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds(),
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        );
      }
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          );
        }
      }
      return fmt;
    } else {
      return '';
    }
  },
  // 格式化金额
  formatMoney(value, currency, decimals) {
    const digitsRE = /(\d{3})(?=\d)/g;
    value = parseFloat(value);
    if (!isFinite(value) || (!value && value !== 0)) return '';
    currency = currency != null ? currency : '￥';
    decimals = decimals != null ? decimals : 2;
    let stringified = Math.abs(value).toFixed(decimals);
    let _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
    let i = _int.length % 3;
    let head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : '';
    let _float = decimals ? stringified.slice(-1 - decimals) : '';
    let sign = value < 0 ? '-' : '';
    return (
      sign + currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float
    );
  },
  // 还原金额格式
  unFormatMoney(value, decimal) {
    value = value || 0;
    if (typeof value === 'number') return value;
    decimal = decimal != null ? decimal : 2;
    let unFormatted = parseFloat(value);
    return !isNaN(unFormatted) ? unFormatted : 0;
  },
  exportExcel(api, name, data = {}) {
    this.$axios({
      method: 'post',
      url: api,
      data: data,
      responseType: 'blob',
    })
      .then((res) => {
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(
            new Blob([res], {
              type: res.type,
            }),
            name + this.$moment().format('YYYYMMDDHHMMSS') + '.xlsx'
          );
        } else {
          let url = window.URL.createObjectURL(
            new Blob([res], {
              type: res.type,
            })
          );
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute(
            'download',
            name + this.$moment().format('YYYYMMDDHHMMSS') + '.xlsx'
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      })
      .catch(() => {});
  },
};
